#include "StdAfx.h"
#include "MultiLineEditUI.h"
#include "BlueRenderEngineUI.h"
#include "MultiLineEditWnd.h"
#include "Rect.h"

CMultiLineEditUI::CMultiLineEditUI(void): m_pWindow(NULL)
{
}

CMultiLineEditUI::~CMultiLineEditUI(void)
{
	if(m_pWindow != NULL && ::IsWindow(*m_pWindow)) 
		m_pWindow->Close();
}

void CMultiLineEditUI::Init()
{
	m_pWindow = new CMultiLineEditWnd();
	ASSERT(m_pWindow);
	m_pWindow->Init(this);
}

LPCTSTR CMultiLineEditUI::GetClass() const
{
	return _T("MultiLineEditUI");
}

UINT CMultiLineEditUI::GetControlFlags() const
{
	return UIFLAG_TABSTOP;
}

void CMultiLineEditUI::SetText(LPCTSTR pstrText)
{
	m_sText = pstrText;
	if( m_pWindow != NULL ) SetWindowText(*m_pWindow, pstrText);
	if( m_pManager != NULL ) m_pManager->SendNotify(this, _T("changed"));
	Invalidate();
}

CStdString CMultiLineEditUI::GetText() const
{
	if( m_pWindow != NULL ) {
		int cchLen = ::GetWindowTextLength(*m_pWindow) + 1;
		LPTSTR pstr = static_cast<LPTSTR>(_alloca(cchLen * sizeof(TCHAR)));
		ASSERT(pstr);
		::GetWindowText(*m_pWindow, pstr, cchLen);
		return CStdString(pstr);
	}
	return m_sText;
}

void CMultiLineEditUI::SetVisible(bool bVisible)
{
	CControlUI::SetVisible(bVisible);
	if( m_pWindow != NULL ) ::ShowWindow(*m_pWindow, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE);
}

void CMultiLineEditUI::SetEnabled(bool bEnabled)
{
	CControlUI::SetEnabled(bEnabled);
	if( m_pWindow != NULL ) ::EnableWindow(*m_pWindow, bEnabled == true);
}

void CMultiLineEditUI::SetReadOnly(bool bReadOnly)
{
	if( m_pWindow != NULL ) Edit_SetReadOnly(*m_pWindow, bReadOnly == true);
	Invalidate();
}

bool CMultiLineEditUI::IsReadOnly() const
{
	return (GetWindowStyle(*m_pWindow) & ES_READONLY) != 0;
}

SIZE CMultiLineEditUI::EstimateSize(SIZE /*szAvailable*/)
{
	return CStdSize(m_rcItem);
}

void CMultiLineEditUI::SetPos(RECT rc)
{
	if( m_pWindow != NULL ) {
		CStdRect rcEdit = rc;
		rcEdit.Deflate(3, 3);
		::SetWindowPos(*m_pWindow, HWND_TOP, rcEdit.left, rcEdit.top, rcEdit.GetWidth(), rcEdit.GetHeight(), SWP_NOACTIVATE);
	}
	CControlUI::SetPos(rc);
}

void CMultiLineEditUI::SetPos(int left, int top, int right, int bottom)
{
	SetPos(CStdRect(left, top, right, bottom));
}

void CMultiLineEditUI::Event(TEventUI& event)
{
	if( event.Type == UIEVENT_WINDOWSIZE )
	{
		if( m_pWindow != NULL ) m_pManager->SetFocus(NULL);
	}
	if( event.Type == UIEVENT_SETFOCUS ) 
	{
		if( m_pWindow != NULL ) ::SetFocus(*m_pWindow);
	}
	CControlUI::Event(event);
}

void CMultiLineEditUI::DoPaint(HDC hDC, const RECT& /*rcPaint*/)
{
	UINT uState = 0;
	if( IsFocused() ) uState |= UISTATE_FOCUSED;
	if( IsReadOnly() ) uState |= UISTATE_READONLY;
	if( !IsEnabled() ) uState |= UISTATE_DISABLED;
	CBlueRenderEngineUI::DoPaintEditBox(hDC, m_pManager, m_rcItem, _T(""), uState, 0, true);
}

